/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.zzb.framework.modules.job.controller;

import com.google.common.collect.Lists;
import com.zzb.framework.common.BasePage;
import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.common.FrameworkException;
import com.zzb.framework.modules.job.entity.ScheduleJobLogEntity;
import com.zzb.framework.modules.job.log.LogResult;
import com.zzb.framework.modules.job.log.XxlJobFileAppender;
import com.zzb.framework.modules.job.service.ScheduleJobLogService;
import com.zzb.framework.modules.role.controller.AbstractController;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 定时任务日志
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/scheduleLog")
public class ScheduleJobLogController extends AbstractController {
    @Autowired
    private ScheduleJobLogService scheduleJobLogService;

    /**
     * 定时任务日志列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:schedule:log")
    public BasePage<ScheduleJobLogEntity> list(@RequestParam Map<String, Object> params) {
        BasePage<ScheduleJobLogEntity> page = scheduleJobLogService.queryPage(params);

        return page;
    }

    /**
     * 定时任务日志信息
     */
    @RequestMapping("/info/{logId}")
    public BaseResponse<ScheduleJobLogEntity> info(@PathVariable("logId") Long logId) {
        ScheduleJobLogEntity log = scheduleJobLogService.getById(logId);
        return BaseResponse.content(log);
    }


    /**系统配置表删除*/
    @PostMapping("/delete")
    @RequiresPermissions("sys:schedule:log:delete")
    public BaseResponse delete(@RequestBody Long[] id) {
        return scheduleJobLogService.deleteByIds(Lists.newArrayList(id));
    }

    @RequestMapping("/logDetailCat")
    public BaseResponse<LogResult> logDetailCat(int logId, int fromLineNum){
        try {
            ScheduleJobLogEntity log = scheduleJobLogService.getById(logId);
            if(log != null) {
                String logFileName = XxlJobFileAppender.makeLogFileName(log.getCreateTime(), logId);

                LogResult logResult = XxlJobFileAppender.readLog(logFileName, fromLineNum);

                // is end
                if (logResult.getFromLineNum() > logResult.getToLineNum()) {
                    logResult.setEnd(true);
                }
                return BaseResponse.content(logResult);
            } else {
                return BaseResponse.error("找不到作业执行日志！");
            }
        } catch (Exception e) {
            return BaseResponse.error(ExceptionUtils.getStackTrace(e));
        }
    }
}
